package com.gitee.huanminabc.fastboot.web.servlet;

import com.gitee.huanminabc.nullchain.common.NullResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-01 18:12
 **/
public class InterfaceExceptionEventFactory {
    //接口错误拦截事件
    public static List<InterfaceExceptionEvent> interfaceErrorEvents = new ArrayList<>();
    public static Map<Class<?>, InterfaceExceptionEvent> interfaceErrorEventsMap = new HashMap<>();

    static {
        //保底异常处理
        registerExceptionEvent(new ThrowableEventHandle());
    }
    //注册事件,支持覆盖系统的异常处理事件
    public  static   void registerExceptionEvent(InterfaceExceptionEvent event) {
        //如果已经注册过了，就删除
        if (interfaceErrorEventsMap.containsKey(event.interceptException())) {
            interfaceErrorEvents.remove(interfaceErrorEventsMap.get(event.interceptException()));
            return;
        }
        interfaceErrorEvents.add(event);
        interfaceErrorEventsMap.put(event.interceptException(), event);
    }

    //执行事件
    public static NullResult<?> executeEvent(Throwable e) {
        //先在map中查找
        InterfaceExceptionEvent event = interfaceErrorEventsMap.get(e.getClass());
        if (event != null) {
            return event.exceptionHandler(e);
        }
        //如果没有找到，就遍历所有的事件
        for (InterfaceExceptionEvent event1 : interfaceErrorEvents) {
            if (event1.interceptException().isInstance(e)) {
                return event1.exceptionHandler(e);
            }
        }
        return NullResult.success();
    }
}
